package cn.edu.suda.catalina.dataupdate.controller;

import cn.edu.suda.catalina.dataupdate.util.ClassNameUtil;
import cn.edu.suda.catalina.dataupdate.util.FileInputUtil;
import cn.edu.suda.catalina.dataupdate.util.JavaCompilerUtil;
import cn.edu.suda.catalina.dataupdate.util.RegexUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by admin on 2017/5/11.
 */
@RestController
public class UploadController {
    public static Map<String, List<Object>> result;

    @RequestMapping("/uploadFile")
    public Map<String, List<Object>> upload(MultipartFile[] files, HttpServletRequest request) {
        result = new HashMap<>();
        String javaFilePath = request.getServletContext().getRealPath("/scripts");
        String dataFilePath = request.getServletContext().getRealPath("/data");
        if (FileInputUtil.mkdirs(javaFilePath) && FileInputUtil.mkdirs(dataFilePath)) {
            for (MultipartFile file : files) {
                String fileName = file.getOriginalFilename();
                if (fileName.endsWith(".java")) {
                    if (FileInputUtil.javaFileInput(javaFilePath, file)) {
                        result.put(ClassNameUtil.getNameWithoutExtensions(fileName), RegexUtil.modify(javaFilePath, ClassNameUtil.getFullName(fileName)));
                        JavaCompilerUtil.compile(javaFilePath, ClassNameUtil.getFullName(fileName));
                    }
                } else {
                    if (FileInputUtil.dataFileInput(dataFilePath, file)) {
                        try {
                            result.put("Option", Arrays.asList(RegexUtil.readLineAsArray(dataFilePath + File.separator + fileName)));
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return result;
    }
}
